package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private SeckillVoucherServiceImpl seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private VoucherOrderServiceImpl voucherOrderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 阻塞队列 当取元素时 没有会阻塞直到有元素
     */
    private BlockingQueue<VoucherOrder> queue = new ArrayBlockingQueue<>(1024 * 1024);

    private ExecutorService seckillExecutor = Executors.newSingleThreadExecutor();

    /**
     * 运行lua脚本的类
     */
    private static final DefaultRedisScript<Long> seckillRedisScript;

    private IVoucherOrderService proxy;

    /**
     * 初始化
     */
    static {
        seckillRedisScript = new DefaultRedisScript<>();
//        seckillRedisScript.setLocation(new ClassPathResource("seckill.lua"));
        seckillRedisScript.setLocation(new ClassPathResource("seckillStream.lua"));
        seckillRedisScript.setResultType(Long.class);
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";


        @Override
        public void run() {
            while (true) {
                try {

                    // 基于jdk的阻塞队列
//                    VoucherOrder take = queue.take();
//                    handleVoucherOrder(take);

                    // 获取消息队列的订单信息 xreadgroup group g1 c1 count 1 block 2000 streams stream.order >     > 未消费 0是已消费但未确认(ack)
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    // 判断信息是否获取成功
                    if(list == null || list.isEmpty()){
                        continue;
                    }

                    // 解析并下单
                    MapRecord<String, Object, Object> first = list.get(0);
                    Map<Object, Object> value = first.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);

                    // ack确认 sack stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",first.getId());

                } catch (Exception e) {
                    log.error("订单异常", e);
                    handlePendingList();
                }
            }

        }


        private void handlePendingList() {
            while (true) {
                try {

                    // 获取pending-list的订单信息 xreadgroup group g1 c1 count 1 streams stream.order 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );

                    // 判断信息是否获取成功
                    if(list == null || list.isEmpty()){
                        break;
                    }

                    // 解析并下单
                    MapRecord<String, Object, Object> first = list.get(0);
                    Map<Object, Object> value = first.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);

                    // ack确认 sack stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",first.getId());

                } catch (Exception e) {
                    log.error("pending订单异常", e);
//                    handlePendingList();
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder take) {
        Long userId = take.getId();

        RLock lock = redissonClient.getLock("lock:order:" + userId); // 使用redisson的锁
        boolean res = lock.tryLock();

        if (!res) {
            log.error("不允许重复下单");
            return;
        }

        try {
            proxy.createVoucherOrderLua(take);
        } finally {
//            simpleRedisLock.unlock();
            lock.unlock();
        }

    }

    @Transactional
    public void createVoucherOrderLua(VoucherOrder voucherOrder){
        // 一人一单
        int count = query().eq("user_id", voucherOrder.getUserId()).eq("voucher_id", voucherOrder.getVoucherId()).count();
        if (count > 0) {
            log.error("下单失败");
            return;
        }

        // 扣减库存
        // 会有并发问题 库存超卖
//        boolean status = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .update();

        // CAS法解决库存超卖 但成功率太低
//        boolean status = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .eq("stock",seckillVoucher.getStock())
//                .update();

        // 这时把 库存大于 0 就可以 增加成功率
        boolean status = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();

        if (!status) {
            return;
        }

        save(voucherOrder);
    }

    @PostConstruct
    private void init() {
        seckillExecutor.execute(new VoucherOrderHandler());
    }

    /**
     * 所用Redis的Stream队列实现
     */
    @Override
    public Result seckill(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        long nextId = redisIdWorker.nextId("order");
        // 执行lua脚本
        Long result = stringRedisTemplate.execute(
                seckillRedisScript,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(nextId)
        );

        int res = result.intValue();
        if (res != 0) {
            // 没有购买资格
            return Result.fail(res == 1 ? "库存不足" : "不能重复下单");
        }

        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 返回订单id
        return Result.ok(nextId);
    }


    /**
     * lua脚本实现一人一单
     */
//    @Override
//    public Result seckill(Long voucherId) {
//
//        Long userId = UserHolder.getUser().getId();
//
//        // 执行lua脚本
//        Long result = stringRedisTemplate.execute(
//                seckillRedisScript,
//                Collections.emptyList(),
//                voucherId.toString(), userId.toString()
//        );
//
//        int res = result.intValue();
//        if (res != 0) {
//            // 没有购买资格
//            return Result.fail(res == 1 ? "库存不足" : "不能重复下单");
//        }
//
//        // 保存到阻塞队列
//        long nextId = redisIdWorker.nextId("order");
//
//        // 创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//
//        // 设置id 用户id 优惠卷id
//        voucherOrder.setId(nextId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//
//        // 放入阻塞队列
//        queue.add(voucherOrder);
//
//        proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//        // 返回订单id
//        return Result.ok(nextId);
//    }


    /**
     * 使用Redisson实现一人一单
     */
//    @Override
//    public Result seckill(Long voucherId) {
//
//        // 查询优惠卷秒杀
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//
//        // 判断秒杀是否开始
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            // 尚未开始
//            return Result.fail("优惠卷未开始");
//        }
//
//        // 判断秒杀是否结束
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            // 结束了
//            return Result.fail("优惠卷已结束");
//        }
//
//        // 判断库存是否充足
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("优惠卷库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//
//        // 使用Redis的锁
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + userId); // 使用redisson的锁
////        boolean res = simpleRedisLock.tryLock(1200);
//        boolean res = lock.tryLock();
//
//        if (!res) {
//            return Result.fail("不允许重复下单");
//        }
//
//        try {
//            IVoucherOrderService iVoucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
//            return iVoucherOrderService.createVoucherOrder(voucherId);
//        } finally {
////            simpleRedisLock.unlock();
//            lock.unlock();
//        }
//
////        synchronized (userId.toString().intern()) {
////            // 这样写会事务会失效因为方法交给了spring @Transactional 来管理
////            // 而spring事务是用代理对象来的
////            // synchronized 里调用方法是加this.XX 不是调用的代理对象的方法 而是自身的方法
//////            return createVoucherOrder(voucherId);
////
////            // 这里也可以注入自己的实现类 现实
////
////            // 通过获取代理对象来进行方法调用 这样可以进行事务处理
////            IVoucherOrderService iVoucherOrderService = (IVoucherOrderService) AopContext.currentProxy();
////            return iVoucherOrderService.createVoucherOrder(voucherId);
////
////        }
//    }
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();


        // 一人一单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) {
            return Result.fail("该优惠卷只能下单一次");
        }

        // 扣减库存
        // 会有并发问题 库存超卖
//        boolean status = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .update();

        // CAS法解决库存超卖 但成功率太低
//        boolean status = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .eq("stock",seckillVoucher.getStock())
//                .update();

        // 这时把 库存大于 0 就可以 增加成功率
        boolean status = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();

        if (!status) {
            return Result.fail("优惠卷库存不足");
        }

        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long nextId = redisIdWorker.nextId("order");

        // 设置id 用户id 优惠卷id
        voucherOrder.setId(nextId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);

        save(voucherOrder);

        return Result.ok(nextId);
    }

}
